/*
 * @Description: 用户信息
 * @Date: 2025-07-09 18:47:26
 * @LastEditors: ocean
 * @LastEditTime: 2025-07-10 11:42:43
 * @FilePath: \uview2.0-template\store\modules\user.js
 */
import { ACCESS_TOKEN } from '@/store/mutation-types'
import storage from '@/utils/storage'
import * as LoginApi from '@/api/login'

// 登陆成功后执行
const loginSuccess = (commit, data) => {
  if (data.code == 1)
  {
      // 保存tokne和userId到缓存
      storage.set("USER_INFO", data.data);
      // 记录到store全局变量
      commit("SET_USER", data.data);
      // 过期时间30天
      const expiryTime = 30 * 86400;
      // 保存tokne和userId到缓存
      storage.set(ACCESS_TOKEN, data.data.Authorization, expiryTime);
      // 记录到store全局变量
      commit("SET_TOKEN", data.data.Authorization);
  }
    
};

export const state = {
  // 用户认证token
  token: '',
  // 用户信息
  userInfo: null
}

export const mutations = {
  SET_TOKEN: (state, value) => {
    state.token = value
  },
  SET_USER: (state, value) => {
    state.userInfo = value
  },
}

export const actions = {

  // 用户登录(普通登录: 输入账号、密码和验证码)
  Login({ commit }, data) {
    return new Promise((resolve, reject) => {
      LoginApi.login(data, { custom: { catch: true } }).then(response => {
          const result = response;
        loginSuccess(commit, result)
        commit("SET_USER", result);
          resolve(response)
        }).catch(reject)
    })
  },

  // 退出登录
  Logout({ commit }, data) {
    return new Promise((resolve, reject) => {
      storage.remove(ACCESS_TOKEN);
      commit("SET_TOKEN", "");
      storage.remove("USER_INFO");
      commit("SET_USER", null);
      // LoginApi.logout(data, { custom: { catch: true } }).then(response => {
      //   storage.remove(ACCESS_TOKEN)
      //   commit('SET_TOKEN', '')
      //   resolve(response)
      // }).catch(reject)
    })
  }

}
